import React, { useState, useEffect } from 'react';
import {
  listDomains,
  startDomain,
  stopDomain,
  forceStopDomain, // 添加强制关机功能
  pauseDomain,
  resumeDomain,
  restartDomain,
  deleteDomain,
  forceDeleteDomain, // 添加强制删除功能
  getVNCInfo
} from '../api/client';
import CreateVMWizardPodmanStyle from '../components/CreateVMWizardPodmanStyle';
import EditVMDialog from '../components/EditVMDialog';
import VNCManager from '../components/VNCManager';
import ConsoleTerminal from '../components/ConsoleTerminal';
import SnapshotManager from '../components/SnapshotManager';
import './VirtualMachines.css';

interface Domain {
  uuid: string;
  name: string;
  status: string;
  cpu: string;
  memory: string;
  state: string;
  cpus: number;
  memoryBytes: number;
  maxMem: number;
  autostart: boolean;
  persistent: boolean;
}

const VirtualMachines: React.FC = () => {
  const [domains, setDomains] = useState<Domain[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [viewMode, setViewMode] = useState<'table' | 'grid'>('table');
  const [filterStatus, setFilterStatus] = useState<string>('all');
  const [searchTerm, setSearchTerm] = useState<string>('');
  const [selectedDomains, setSelectedDomains] = useState<Set<string>>(new Set());
  const [sortBy, setSortBy] = useState<'name' | 'status' | 'cpu' | 'memory'>('name');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc');
  const [notification, setNotification] = useState<{ message: string; type: 'success' | 'error' | 'info' } | null>(null);
  const [showCreateWizard, setShowCreateWizard] = useState(false);
  const [showAdvancedFilters, setShowAdvancedFilters] = useState(false);

  // VNC and Console states
  const [showVNCManager, setShowVNCManager] = useState(false);
  const [showConsoleTerminal, setShowConsoleTerminal] = useState(false);
  const [selectedVMForConnection, setSelectedVMForConnection] = useState<string | null>(null);
  const [consoleType, setConsoleType] = useState<'console' | 'serial' | 'parallel' | 'channel'>('console');
  const [consoleWebSocketURL, setConsoleWebSocketURL] = useState<string | null>(null);

  // Snapshot management states
  const [showSnapshotManager, setShowSnapshotManager] = useState(false);
  const [selectedVMForSnapshots, setSelectedVMForSnapshots] = useState<string | null>(null);

  // VM editing states
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [selectedVMForEdit, setSelectedVMForEdit] = useState<Domain | null>(null);

  // Notification system
  const showNotification = (message: string, type: 'success' | 'error' | 'info') => {
    setNotification({ message, type });
    setTimeout(() => setNotification(null), 3000);
  };

  // Sorting and filtering functions
  const sortDomains = (domains: Domain[]) => {
    return [...domains].sort((a, b) => {
      let aValue: string | number;
      let bValue: string | number;

      switch (sortBy) {
        case 'name':
          aValue = a.name.toLowerCase();
          bValue = b.name.toLowerCase();
          break;
        case 'status':
          aValue = a.status;
          bValue = b.status;
          break;
        case 'cpu':
          aValue = a.cpus;
          bValue = b.cpus;
          break;
        case 'memory':
          aValue = parseFloat(a.memory);
          bValue = parseFloat(b.memory);
          break;
        default:
          aValue = a.name.toLowerCase();
          bValue = b.name.toLowerCase();
      }

      if (sortOrder === 'asc') {
        return aValue < bValue ? -1 : aValue > bValue ? 1 : 0;
      } else {
        return aValue > bValue ? -1 : aValue < bValue ? 1 : 0;
      }
    });
  };

  const filterAndSearchDomains = (domains: Domain[]) => {
    return domains.filter(domain => {
      // Status filter
      if (filterStatus !== 'all' && domain.status !== filterStatus) {
        return false;
      }

      // Search filter
      if (searchTerm && !domain.name.toLowerCase().includes(searchTerm.toLowerCase())) {
        return false;
      }

      return true;
    });
  };

  // Bulk operations
  const handleBulkOperation = async (operation: string) => {
    if (selectedDomains.size === 0) {
      showNotification('请选择虚拟机进行批量操作', 'info');
      return;
    }

    const selectedUUIDs = Array.from(selectedDomains);
    let successCount = 0;
    let errorCount = 0;
    let errorMessages: string[] = [];

    for (const uuid of selectedUUIDs) {
      try {
        switch (operation) {
          case 'start':
            await startDomain(uuid);
            break;
          case 'stop':
            await stopDomain(uuid);
            break;
          case 'pause':
            await pauseDomain(uuid);
            break;
          case 'resume':
            await resumeDomain(uuid);
            break;
          case 'restart':
            await restartDomain(uuid);
            break;
          case 'delete':
            if (confirm(`确定要删除 ${selectedUUIDs.length} 个虚拟机吗？此操作不可撤销。`)) {
              await deleteDomain(uuid);
            } else {
              return;
            }
            break;
        }
        successCount++;
      } catch (error: any) {
        errorCount++;
        const errorMessage = error.response?.data?.detail || error.response?.data?.error || error.message || '未知错误';
        errorMessages.push(`虚拟机 ${uuid}: ${errorMessage}`);
        console.error(`Failed to ${operation} domain ${uuid}:`, error);
      }
    }

    if (errorCount > 0) {
      const errorSummary = errorMessages.length > 0 ? `\n${errorMessages.join('\n')}` : '';
      showNotification(`${successCount} 个虚拟机操作成功，${errorCount} 个失败${errorSummary}`, 'error');
    } else {
      showNotification(`${successCount} 个虚拟机操作成功`, 'success');
    }

    loadDomains();
    setSelectedDomains(new Set());
  };

  const toggleDomainSelection = (uuid: string) => {
    const newSelected = new Set(selectedDomains);
    if (newSelected.has(uuid)) {
      newSelected.delete(uuid);
    } else {
      newSelected.add(uuid);
    }
    setSelectedDomains(newSelected);
  };

  const selectAllDomains = () => {
    if (selectedDomains.size === filteredDomains.length) {
      setSelectedDomains(new Set());
    } else {
      setSelectedDomains(new Set(filteredDomains.map(d => d.uuid)));
    }
  };

  useEffect(() => {
    loadDomains();
    // Auto-refresh every 10 seconds only when not showing modal dialogs
    let interval: NodeJS.Timeout | null = null;
    
    const shouldAutoRefresh = !showCreateWizard && 
                             !showVNCManager && 
                             !showConsoleTerminal && 
                             !showSnapshotManager && 
                             !showEditDialog;
    
    if (shouldAutoRefresh) {
      interval = setInterval(loadDomains, 10000);
    }
    
    return () => {
      if (interval) {
        clearInterval(interval);
      }
    };
  }, [showCreateWizard, showVNCManager, showConsoleTerminal, showSnapshotManager, showEditDialog]);

  const loadDomains = async () => {
    try {
      setLoading(true); // Show loading spinner
      setError(null);
      const response = await listDomains();

      // Handle both direct array and wrapped response formats
      let domainsArray = [];
      if (response.data && Array.isArray(response.data)) {
        domainsArray = response.data;
      } else if (response.data && response.data.domains && Array.isArray(response.data.domains)) {
        domainsArray = response.data.domains;
      } else if (response.data && response.data.domains === null) {
        // Handle case where there are no domains
        domainsArray = [];
      }

      // Adapt API response format
      const domainData = domainsArray.map((domain: any) => ({
        uuid: domain.uuid || domain.UUID || '',
        name: domain.name || domain.Name || '',
        status: domain.state || domain.State || domain.status || 'unknown',
        state: domain.state || domain.State || domain.status || 'unknown',
        cpu: domain.cpus !== undefined ? `${domain.cpus} vCPU${domain.cpus > 1 ? 's' : ''}` : 'N/A',
        memory: domain.memory ? `${(domain.memory / 1024 / 1024).toFixed(1)} GB` : 'N/A',
        memoryBytes: domain.memory || 0,
        maxMem: domain.maxMem || domain.memory || 0,
        cpus: domain.cpus || 0,
        autostart: domain.autostart !== undefined ? domain.autostart : false,
        persistent: domain.persistent !== undefined ? domain.persistent : false
      }));

      setDomains(domainData);
    } catch (err: any) {
      console.error('Failed to load domains:', err);
      const errorMessage = err.response?.data?.detail || err.response?.data?.error || err.message || '未知错误';
      setError(`加载虚拟机失败: ${errorMessage}`);
      showNotification(`加载虚拟机失败: ${errorMessage}`, 'error');
    } finally {
      setLoading(false);
    }
  };

  // Individual operation handlers
  const handleStart = async (uuid: string) => {
    try {
      await startDomain(uuid);
      loadDomains();
      const domain = domains.find(d => d.uuid === uuid);
      showNotification(`虚拟机 "${domain?.name || uuid}" 启动成功`, 'success');
    } catch (error: any) {
      console.error('Failed to start domain:', error);
      const errorMessage = error.response?.data?.detail || error.response?.data?.error || error.message || '未知错误';
      const domain = domains.find(d => d.uuid === uuid);
      showNotification(`启动虚拟机 "${domain?.name || uuid}" 失败: ${errorMessage}`, 'error');
    }
  };

  const handleStop = async (uuid: string) => {
    try {
      await stopDomain(uuid);
      loadDomains();
      const domain = domains.find(d => d.uuid === uuid);
      showNotification(`虚拟机 "${domain?.name || uuid}" 停止成功`, 'success');
    } catch (error: any) {
      console.error('Failed to stop domain:', error);
      const errorMessage = error.response?.data?.detail || error.response?.data?.error || error.message || '未知错误';
      const domain = domains.find(d => d.uuid === uuid);
      showNotification(`停止虚拟机 "${domain?.name || uuid}" 失败: ${errorMessage}`, 'error');
    }
  };

  const handleForceStop = async (uuid: string) => {
    const domain = domains.find(d => d.uuid === uuid);
    if (!confirm(`确定要强制关闭虚拟机 "${domain?.name || uuid}" 吗？这可能导致数据丢失。`)) {
      return;
    }

    try {
      await forceStopDomain(uuid);
      loadDomains();
      showNotification(`虚拟机 "${domain?.name || uuid}" 强制关闭成功`, 'success');
    } catch (error: any) {
      console.error('Failed to force stop domain:', error);
      const errorMessage = error.response?.data?.detail || error.response?.data?.error || error.message || '未知错误';
      showNotification(`强制关闭虚拟机 "${domain?.name || uuid}" 失败: ${errorMessage}`, 'error');
    }
  };

  const handlePause = async (uuid: string) => {
    try {
      await pauseDomain(uuid);
      loadDomains();
      const domain = domains.find(d => d.uuid === uuid);
      showNotification(`虚拟机 "${domain?.name || uuid}" 暂停成功`, 'success');
    } catch (error: any) {
      console.error('Failed to pause domain:', error);
      const errorMessage = error.response?.data?.detail || error.response?.data?.error || error.message || '未知错误';
      const domain = domains.find(d => d.uuid === uuid);
      showNotification(`暂停虚拟机 "${domain?.name || uuid}" 失败: ${errorMessage}`, 'error');
    }
  };

  const handleResume = async (uuid: string) => {
    try {
      await resumeDomain(uuid);
      loadDomains();
      const domain = domains.find(d => d.uuid === uuid);
      showNotification(`虚拟机 "${domain?.name || uuid}" 恢复成功`, 'success');
    } catch (error: any) {
      console.error('Failed to resume domain:', error);
      const errorMessage = error.response?.data?.detail || error.response?.data?.error || error.message || '未知错误';
      const domain = domains.find(d => d.uuid === uuid);
      showNotification(`恢复虚拟机 "${domain?.name || uuid}" 失败: ${errorMessage}`, 'error');
    }
  };

  const handleRestart = async (uuid: string) => {
    try {
      await restartDomain(uuid);
      loadDomains();
      const domain = domains.find(d => d.uuid === uuid);
      showNotification(`虚拟机 "${domain?.name || uuid}" 重启成功`, 'success');
    } catch (error: any) {
      console.error('Failed to restart domain:', error);
      const errorMessage = error.response?.data?.detail || error.response?.data?.error || error.message || '未知错误';
      const domain = domains.find(d => d.uuid === uuid);
      showNotification(`重启虚拟机 "${domain?.name || uuid}" 失败: ${errorMessage}`, 'error');
    }
  };

  const handleDelete = async (uuid: string) => {
    const domain = domains.find(d => d.uuid === uuid);
    if (!confirm(`确定要删除虚拟机 "${domain?.name || uuid}" 吗？此操作不可撤销。`)) {
      return;
    }

    try {
      await deleteDomain(uuid);
      loadDomains();
      showNotification(`虚拟机 "${domain?.name || uuid}" 删除成功`, 'success');
    } catch (error: any) {
      console.error('Failed to delete domain:', error);
      const errorMessage = error.response?.data?.detail || error.response?.data?.error || error.message || '未知错误';
      showNotification(`删除虚拟机 "${domain?.name || uuid}" 失败: ${errorMessage}`, 'error');
    }
  };

  const handleForceDelete = async (uuid: string) => {
    const domain = domains.find(d => d.uuid === uuid);
    if (!confirm(`确定要强制删除虚拟机 "${domain?.name || uuid}" 吗？此操作不可撤销，且可能导致数据丢失。`)) {
      return;
    }

    try {
      await forceDeleteDomain(uuid);
      loadDomains();
      showNotification(`虚拟机 "${domain?.name || uuid}" 强制删除成功`, 'success');
    } catch (error: any) {
      console.error('Failed to force delete domain:', error);
      const errorMessage = error.response?.data?.detail || error.response?.data?.error || error.message || '未知错误';
      showNotification(`强制删除虚拟机 "${domain?.name || uuid}" 失败: ${errorMessage}`, 'error');
    }
  };

  // VNC and Console handlers
  const handleOpenVNCManager = (uuid: string) => {
    setSelectedVMForConnection(uuid);
    setShowVNCManager(true);
  };

  const handleOpenConsole = async (uuid: string, type: 'console' | 'serial' | 'parallel' | 'channel' = 'console') => {
    setSelectedVMForConnection(uuid);
    setConsoleType(type);

    try {
      const vncResponse = await getVNCInfo(uuid);
      setConsoleWebSocketURL(vncResponse.data.console_websocket_url);
    } catch (err) {
      console.warn('Failed to get VNC info for console:', err);
      setConsoleWebSocketURL(null);
    }

    setShowConsoleTerminal(true);
  };

  const handleCloseVNCManager = () => {
    setShowVNCManager(false);
    setSelectedVMForConnection(null);
  };

  const handleCloseConsole = () => {
    setShowConsoleTerminal(false);
    setSelectedVMForConnection(null);
    setConsoleWebSocketURL(null);
  };

  // Snapshot management handlers
  const handleOpenSnapshots = (uuid: string) => {
    setSelectedVMForSnapshots(uuid);
    setShowSnapshotManager(true);
  };

  const handleCloseSnapshots = () => {
    setShowSnapshotManager(false);
    setSelectedVMForSnapshots(null);
  };

  // VM editing handlers
  const handleOpenEditDialog = (uuid: string) => {
    const domain = domains.find(d => d.uuid === uuid);
    if (domain) {
      setSelectedVMForEdit(domain);
      setShowEditDialog(true);
    }
  };

  const handleCloseEditDialog = () => {
    setShowEditDialog(false);
    setSelectedVMForEdit(null);
  };

  const handleEditSuccess = (updatedVM: any) => {
    showNotification(`虚拟机 "${updatedVM.name}" 更新成功`, 'success');
    loadDomains();
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'running': return 'running';
      case 'shutoff': return 'stopped';
      case 'paused': return 'paused';
      default: return 'unknown';
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'running': return '▶️';
      case 'shutoff': return '⏹️';
      case 'paused': return '⏸️';
      default: return '⚪';
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'running': return '运行中';
      case 'shutoff': return '已停止';
      case 'paused': return '已暂停';
      default: return '未知';
    }
  };

  // Filter and search domains
  const filteredDomains = domains.filter(domain => {
    // Status filter
    if (filterStatus !== 'all' && domain.status !== filterStatus) {
      return false;
    }

    // Search filter
    if (searchTerm && !domain.name.toLowerCase().includes(searchTerm.toLowerCase())) {
      return false;
    }

    return true;
  });

  // Sort domains
  const sortedAndFilteredDomains = sortDomains(filteredDomains);

  if (loading && domains.length === 0) {
    return (
      <div className="vm-page">
        <div className="page-header">
          <h1>虚拟机</h1>
        </div>
        <div className="loading-container">
          <div className="loading-spinner"></div>
          <p>正在加载虚拟机...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="vm-page">
        <div className="page-header">
          <h1>虚拟机</h1>
        </div>
        <div className="error-card">
          <div className="error-icon">⚠️</div>
          <h3>连接错误</h3>
          <p>{error}</p>
          <button onClick={loadDomains} className="btn-primary">
            重试
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="vm-page">
      {/* Notification System */}
      {notification && (
        <div className={`notification notification-${notification.type}`}>
          <span className="notification-icon">
            {notification.type === 'success' ? '✅' : notification.type === 'error' ? '❌' : 'ℹ️'}
          </span>
          <span className="notification-message">{notification.message}</span>
          <button
            className="notification-close"
            onClick={() => setNotification(null)}
          >
            ✕
          </button>
        </div>
      )}

      {/* Header - Consistent with Networks Page */}
      <div className="page-header">
        <div className="header-content">
          <h1>虚拟机</h1>
          <div className="header-meta">
            <span className="vm-count">{filteredDomains.length} 个虚拟机</span>
            <span className="running-count">{domains.filter(d => d.status === 'running').length} 个运行中</span>
            {selectedDomains.size > 0 && (
              <span className="selection-count">{selectedDomains.size} 个已选择</span>
            )}
          </div>
        </div>
        <div className="header-actions">
          {/* Search */}
          <div className="search-group">
            <input
              type="text"
              className="search-input"
              placeholder="搜索虚拟机..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
          </div>

          {/* Filter */}
          <div className="filter-group">
            <select
              className="filter-select"
              value={filterStatus}
              onChange={(e) => setFilterStatus(e.target.value)}
            >
              <option value="all">全部状态</option>
              <option value="running">运行中</option>
              <option value="shutoff">已停止</option>
              <option value="paused">已暂停</option>
            </select>
          </div>

          {/* View Toggle */}
          <div className="view-toggle">
            <button
              className={`view-btn ${viewMode === 'table' ? 'active' : ''}`}
              onClick={() => setViewMode('table')}
              title="表格视图"
            >
              ☰
            </button>
            <button
              className={`view-btn ${viewMode === 'grid' ? 'active' : ''}`}
              onClick={() => setViewMode('grid')}
              title="卡片视图"
            >
              ⊞
            </button>
          </div>

          {/* Bulk Actions */}
          {selectedDomains.size > 0 && (
            <div className="bulk-group">
              <select
                defaultValue=""
                onChange={(e) => {
                  if (e.target.value) {
                    handleBulkOperation(e.target.value);
                    e.target.value = '';
                  }
                }}
                className="bulk-select"
              >
                <option value="">批量操作 ({selectedDomains.size})</option>
                <option value="start">启动全部</option>
                <option value="stop">停止全部</option>
                <option value="pause">暂停全部</option>
                <option value="resume">恢复全部</option>
                <option value="restart">重启全部</option>
                <option value="delete">删除全部</option>
              </select>
            </div>
          )}

          {/* Refresh */}
          <button
            onClick={loadDomains}
            disabled={loading}
            title="刷新"
          >
            ↻
          </button>

          {/* Advanced Filters */}
          <button
            className="secondary"
            onClick={() => setShowAdvancedFilters(!showAdvancedFilters)}
          >
            高级筛选
          </button>

          {/* Create VM */}
          <button
            className="primary"
            onClick={() => setShowCreateWizard(true)}
          >
            + 新建虚拟机
          </button>
        </div>
      </div>

      {/* Advanced Filters */}
      {showAdvancedFilters && (
        <div className="advanced-filters">
          <div className="filter-section">
            <label>排序方式:</label>
            <select
              value={sortBy}
              onChange={(e) => setSortBy(e.target.value as any)}
              className="filter-select"
            >
              <option value="name">名称</option>
              <option value="status">状态</option>
              <option value="cpu">CPU</option>
              <option value="memory">内存</option>
            </select>
            <button
              className="btn-icon"
              onClick={() => setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')}
              title={sortOrder === 'asc' ? '升序' : '降序'}
            >
              {sortOrder === 'asc' ? '↑' : '↓'}
            </button>
          </div>
        </div>
      )}

      {/* Bulk Selection Bar */}
      {selectedDomains.size > 0 && (
        <div className="bulk-selection-bar">
          <span className="selection-count">已选择 {selectedDomains.size} 个虚拟机</span>
          <button
            className="btn-secondary"
            onClick={selectAllDomains}
          >
            {selectedDomains.size === filteredDomains.length ? '取消全选' : '全选'}
          </button>
        </div>
      )}

      {/* Content */}
      {sortedAndFilteredDomains.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">🖥️</div>
          <h3>暂无虚拟机</h3>
          <p>开始创建您的第一个虚拟机</p>
          <button
            className="btn-primary"
            onClick={() => setShowCreateWizard(true)}
          >
            创建虚拟机
          </button>
        </div>
      ) : viewMode === 'table' ? (
        /* Table View */
        <div className="vm-table-container">
          <table className="vm-table">
            <thead>
              <tr>
                <th className="select-cell">
                  <input
                    type="checkbox"
                    checked={selectedDomains.size === filteredDomains.length && filteredDomains.length > 0}
                    onChange={selectAllDomains}
                    className="vm-checkbox"
                  />
                </th>
                <th className="name-cell">名称</th>
                <th className="status-cell">状态</th>
                <th className="cpu-cell">CPU</th>
                <th className="memory-cell">内存</th>
                <th className="autostart-cell">自动启动</th>
                <th className="actions-cell">操作</th>
              </tr>
            </thead>
            <tbody>
              {sortedAndFilteredDomains.map((domain) => (
                <tr key={domain.uuid} className={selectedDomains.has(domain.uuid) ? 'selected' : ''}>
                  <td className="select-cell">
                    <input
                      type="checkbox"
                      checked={selectedDomains.has(domain.uuid)}
                      onChange={() => toggleDomainSelection(domain.uuid)}
                      className="vm-checkbox"
                    />
                  </td>
                  <td className="name-cell">
                    <div className="vm-name-wrapper">
                      <span className="vm-name" title={domain.name}>{domain.name}</span>
                    </div>
                  </td>
                  <td className="status-cell">
                    <div className={`status-badge ${getStatusColor(domain.status)}`}>
                      <span className="status-icon">{getStatusIcon(domain.status)}</span>
                      <span className="status-text">{getStatusText(domain.status)}</span>
                    </div>
                  </td>
                  <td className="cpu-cell">{domain.cpu}</td>
                  <td className="memory-cell">{domain.memory}</td>
                  <td className="autostart-cell">
                    <span className={`autostart-indicator ${domain.autostart ? 'enabled' : 'disabled'}`}>
                      {domain.autostart ? '是' : '否'}
                    </span>
                  </td>
                  <td className="actions-cell">
                    <div className="table-actions">
                      {domain.status === 'shutoff' && (
                        <button
                          className="success"
                          onClick={() => handleStart(domain.uuid)}
                          title="启动"
                        >
                          ▶️
                        </button>
                      )}
                      {domain.status === 'running' && (
                        <>
                          <button
                            className="danger"
                            onClick={() => handleStop(domain.uuid)}
                            title="停止"
                          >
                            ⏹️
                          </button>
                          <button
                            className="danger force"
                            onClick={() => handleForceStop(domain.uuid)}
                            title="强制停止"
                          >
                            ⏹️!
                          </button>
                          <button
                            className="primary"
                            onClick={() => handlePause(domain.uuid)}
                            title="暂停"
                          >
                            ⏸️
                          </button>
                          <button
                            className="primary"
                            onClick={() => handleRestart(domain.uuid)}
                            title="重启"
                          >
                            🔄
                          </button>
                        </>
                      )}
                      {domain.status === 'paused' && (
                        <button
                          className="success"
                          onClick={() => handleResume(domain.uuid)}
                          title="恢复"
                        >
                          ▶️
                        </button>
                      )}
                      <button
                        className="secondary"
                        onClick={() => handleOpenConsole(domain.uuid)}
                        title="控制台"
                      >
                        🖥️
                      </button>
                      <button
                        className="secondary"
                        onClick={() => handleOpenVNCManager(domain.uuid)}
                        title="VNC"
                      >
                        🖼️
                      </button>
                      <button
                        className="secondary"
                        onClick={() => handleOpenSnapshots(domain.uuid)}
                        title="快照"
                      >
                        📸
                      </button>
                      <button
                        className="info"
                        onClick={() => handleOpenEditDialog(domain.uuid)}
                        title="编辑"
                      >
                        ✏️
                      </button>
                      <button
                        className="danger"
                        onClick={() => handleDelete(domain.uuid)}
                        title="删除"
                      >
                        🗑️
                      </button>
                      <button
                        className="danger force"
                        onClick={() => handleForceDelete(domain.uuid)}
                        title="强制删除"
                      >
                        🗑️!
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        /* Grid View - Consistent with Networks */
        <div className="vm-grid">
          {sortedAndFilteredDomains.map((domain) => (
            <div
              key={domain.uuid}
              className={`vm-card ${selectedDomains.has(domain.uuid) ? 'selected' : ''}`}
            >
              {/* Selection Checkbox */}
              <div className="selection-checkbox">
                <input
                  type="checkbox"
                  className="vm-checkbox"
                  checked={selectedDomains.has(domain.uuid)}
                  onChange={() => toggleDomainSelection(domain.uuid)}
                />
              </div>

              <div className="vm-card-header">
                <div className="vm-card-header-left">
                  <div className={`status-badge ${getStatusColor(domain.status)}`}>
                    <span className="status-icon">{getStatusIcon(domain.status)}</span>
                    <span className="status-text">{getStatusText(domain.status)}</span>
                  </div>
                </div>
                <div className="vm-card-header-right">
                  <h3 className="vm-name" title={domain.name}>{domain.name}</h3>
                </div>
              </div>

              <div className="vm-card-body">
                <div className="vm-specs">
                  <div className="spec-item">
                    <span className="spec-label">CPU</span>
                    <span className="spec-value">{domain.cpu}</span>
                  </div>
                  <div className="spec-item">
                    <span className="spec-label">内存</span>
                    <span className="spec-value">{domain.memory}</span>
                  </div>
                  <div className="spec-item">
                    <span className="spec-label">自动启动</span>
                    <span className={`autostart-indicator ${domain.autostart ? 'enabled' : 'disabled'}`}>
                      {domain.autostart ? '是' : '否'}
                    </span>
                  </div>
                </div>
              </div>

              <div className="vm-actions">
                <div className="vm-actions-primary">
                  {domain.status === 'shutoff' && (
                    <button
                      className="primary"
                      onClick={() => handleStart(domain.uuid)}
                    >
                      启动
                    </button>
                  )}
                  {domain.status === 'running' && (
                    <>
                      <button
                        className="warning"
                        onClick={() => handleStop(domain.uuid)}
                      >
                        停止
                      </button>
                      <button
                        className="primary"
                        onClick={() => handlePause(domain.uuid)}
                      >
                        暂停
                      </button>
                    </>
                  )}
                  {domain.status === 'paused' && (
                    <button
                      className="primary"
                      onClick={() => handleResume(domain.uuid)}
                    >
                      恢复
                    </button>
                  )}
                </div>
                <div className="vm-actions-secondary">
                  <button
                    className="secondary"
                    onClick={() => handleOpenConsole(domain.uuid)}
                    title="控制台"
                  >
                    🖥️
                  </button>
                  <button
                    className="secondary"
                    onClick={() => handleOpenVNCManager(domain.uuid)}
                    title="VNC"
                  >
                    🖼️
                  </button>
                  <button
                    className="secondary"
                    onClick={() => handleOpenSnapshots(domain.uuid)}
                    title="快照"
                  >
                    📸
                  </button>
                  <button
                    className="info"
                    onClick={() => handleOpenEditDialog(domain.uuid)}
                    title="编辑"
                  >
                    ✏️
                  </button>
                  <button
                    className="danger"
                    onClick={() => handleDelete(domain.uuid)}
                    title="删除"
                  >
                    删除
                  </button>
                  <button
                    className="danger force"
                    onClick={() => handleForceDelete(domain.uuid)}
                  >
                    强制删除
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Create VM Wizard */}
      <CreateVMWizardPodmanStyle
        isOpen={showCreateWizard}
        onClose={() => setShowCreateWizard(false)}
        onSuccess={(vm) => {
          showNotification(`虚拟机 "${vm.name}" 创建成功`, 'success');
          // 只在创建成功后刷新虚拟机列表
          setTimeout(() => {
            loadDomains();
          }, 1000);
        }}
      />

      {/* VNC Manager Modal */}
      <VNCManager
        domainName={selectedVMForConnection || ''}
        isOpen={showVNCManager}
        onClose={handleCloseVNCManager}
      />

      {/* Console Terminal Modal */}
      <ConsoleTerminal
        domainName={selectedVMForConnection || ''}
        consoleType={consoleType}
        isOpen={showConsoleTerminal}
        onClose={handleCloseConsole}
        consoleWebSocketURL={consoleWebSocketURL}
      />

      {/* Snapshot Manager Modal */}
      {showSnapshotManager && selectedVMForSnapshots && (
        <div className="modal-overlay" onClick={handleCloseSnapshots}>
          <div className="modal-content large" onClick={(e) => e.stopPropagation()}>
            <div className="modal-header">
              <h2>管理快照 - {domains.find(d => d.uuid === selectedVMForSnapshots)?.name}</h2>
              <button
                className="modal-close"
                onClick={handleCloseSnapshots}
              >
                ✕
              </button>
            </div>
            <div className="modal-body">
              <SnapshotManager
                domainName={domains.find(d => d.uuid === selectedVMForSnapshots)?.name || ''}
                onNotification={showNotification}
              />
            </div>
            <div className="modal-footer">
              <button
                className="btn-secondary"
                onClick={handleCloseSnapshots}
              >
                关闭
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Edit VM Dialog */}
      <EditVMDialog
        isOpen={showEditDialog}
        onClose={handleCloseEditDialog}
        onSuccess={handleEditSuccess}
        domain={selectedVMForEdit ? {
          uuid: selectedVMForEdit.uuid,
          name: selectedVMForEdit.name,
          memory: selectedVMForEdit.memoryBytes,
          cpus: selectedVMForEdit.cpus,
          autostart: selectedVMForEdit.autostart,
          state: selectedVMForEdit.state
        } : null}
      />
    </div>
  );
};

export default VirtualMachines;